package com.example.EL;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author kongwg
 * @create 2021-01-25 9:32
 */
@WebServlet("/upload")
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)){

            FileItemFactory fif = new DiskFileItemFactory();
              ServletFileUpload fileUpload = new ServletFileUpload(fif);

            try {
                List<FileItem> list = fileUpload.parseRequest(req);

                for (FileItem fileItem : list){
                    if (fileItem.isFormField()){
                        System.out.println("属性的名字"+fileItem.getFieldName());
                        System.out.println("属性的值"+fileItem.getString());
                    }else {
                        System.out.println("上传文件属性名"+fileItem.getFieldName());
                        System.out.println("上传文件的名字"+ fileItem.getName());
                        fileItem.write(new File("E:/"+fileItem.getName()));


                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}
